/*************************************************************************
	> File Name: P1591.cpp
	> Author: yufangze
	> Mail: 2224590123@qq.com
	> Created Time: 2025-01-09 10:32:57
 ************************************************************************/

#include <iostream>
#include <set>
#include <map>
#include <vector>
#include <algorithm>
using namespace std;

class BigInt : public vector<int> {
public:
    BigInt() {push_back(0);}
    BigInt(int x) {
        push_back(x);
        proccess_digit();
    }
    
    BigInt &operator*=(const int x) {
        for (int i = 0; i < size(); i++) {
            at(i) *= x;
        }
        proccess_digit();
        return *this;
    }

private:
    void proccess_digit() {
        for (int i = 0; i < size(); i++) {
            if (at(i) < 10) continue;
            if (i + 1 == size()) push_back(0);
            at(i + 1) += at(i) / 10;
            at(i) %= 10;
        }
        while (size() > 1 && back() == 0) pop_back();
    }
};

int calc(int n, int x) {
    BigInt ans = 1;
    for (int i = 2; i <= n; i++) {
        ans *= i;
    }
    int cnt = 0;
    for (int i = 0; i < ans.size(); i++) {
        cnt += (ans[i] == x);
    }
    return cnt;
}

int main() {
    int t;
    cin >> t;
    while (t--) {
        int n, x;
        cin >> n >> x;
        cout << calc(n, x) << endl;
    }
    return 0;
}
